/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-2-4 下午3:57 Created by dwzhang
 */
package com.jade.bss.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.jade.bss.base.RoleAction;
import com.jade.bss.base.customer.Customer;
import com.jade.framework.base.criterion.*;
import com.jade.framework.base.util.PagingList;
import com.jade.framework.base.util.PagingResult;
import com.jade.framework.base.util.ResponseUtils;
import com.jade.modules.config.ConfigEntity;
import com.jade.modules.config.ConfigGroupEntity;
import com.jade.modules.config.ConfigUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

/**
 * 配置项控制器
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a>
 * @version 1.0 15-1-15 下午6:45
 */
@RestController
@RequestMapping (value = "/config", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "选项设置", description = "系统配置--配置项管理")
public class ConfigController
{
    /**************************主表信息****************************/
    @RequestMapping (value = RoleAction.QUERY, method = RequestMethod.GET)
    @ApiOperation(value = "查询选项", httpMethod = "GET", response = ConfigGroupEntity.class)
    public void query(@ApiParam("关键词") @RequestParam (value = "keyword", required = false) String keyword,
                      @ApiParam("起始值") @RequestParam (value = "offset") int offset,
                      @ApiParam("每页大小") @RequestParam (value = "length") int length,
                      @ApiParam("排序字段") @RequestParam (value = "sort", required = false) String sort,
                      @ApiParam("排序规则") @RequestParam (value = "order", required = false) String order,
                      HttpServletResponse response)
            throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        Criteria criteria = new Criteria(offset, length);
        if(StringUtils.isNotBlank(keyword))
            CriterionUtils.addQuery(criteria,new String[]{"key","value"},keyword, MatchMode.ANYWHERE,null);
        criteria.add(Restrictions.eq("ownerId", customer.getOwnerId()));
        CriterionUtils.addOrder(criteria, sort, order, "orderCode");
        PagingList<ConfigGroupEntity> entities = ConfigUtils.queryGroup(customer.getOwnerType(),customer.getOwnerId(), criteria);
        PagingResult result = PagingResult.getResult(entities);
        ResponseUtils.writeSuccessPagingResult(response, result);
    }

    @RequiresAuthentication
    @RequestMapping (value = RoleAction.ADD, method = RequestMethod.POST)
    @ApiOperation(value = "增加选项", httpMethod = "POST")
    public void add(@ApiParam(value = "组对象", required = true) @RequestBody ConfigGroupEntity groupEntity, HttpServletResponse response)
            throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        groupEntity.setOwnerType(customer.getOwnerType());
        groupEntity.setOwnerId(customer.getOwnerId());
        groupEntity.setUpdateTime(new Date());
        ConfigUtils.addGroup(groupEntity);
        ResponseUtils.writeSuccessResult(response);
    }
    @RequiresAuthentication
    @RequestMapping (value = RoleAction.GET, method = RequestMethod.GET)
    @ApiOperation(value = "获取选项", httpMethod = "GET")
    public void GET(@ApiParam(value = "组id", required = true) @PathVariable long id, HttpServletResponse response)
            throws Exception
    {
        ConfigGroupEntity groupEntity = ConfigUtils.getGroup(id);
        ResponseUtils.writeSuccessResult(response, groupEntity);
    }


    @RequiresAuthentication
    @RequestMapping (value = RoleAction.UPDATE, method = RequestMethod.PUT)
    @ApiOperation(value = "修改选项", httpMethod = "PUT")
    public void UPDATE(@ApiParam(value = "组对象", required = true) @RequestBody ConfigGroupEntity groupEntity, HttpServletResponse response)
            throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        groupEntity.setOwnerType(customer.getOwnerType());
        groupEntity.setOwnerId(customer.getOwnerId());
        groupEntity.setUpdateTime(new Date());
        ConfigUtils.updateGroup(groupEntity);
        ResponseUtils.writeSuccessResult(response);
    }

    @RequiresAuthentication
    @RequestMapping (value = RoleAction.DELETE, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除选项", httpMethod = "DELETE")
    public void DELETE(@RequestParam ("id") long[] ids, HttpServletResponse response)
            throws Exception
    {
        ConfigUtils.removeGroup(ids);
        ResponseUtils.writeSuccessResult(response);
    }

    @RequiresAuthentication
    @RequestMapping (value = "/get", method = RequestMethod.GET)
    @ApiOperation(value = "根据KEY获取选项", httpMethod = "GET")
    public void getGroup(@RequestParam ("key") String key,  HttpServletResponse response) throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        ResponseUtils.writeSuccessResult(response, ConfigUtils.getGroup(customer.getOwnerType(), customer.getOwnerId(),key));
    }

    /***********************明细信息***************************/
    @RequestMapping (value = RoleAction.QUERYDetail, method = RequestMethod.GET)
    @ApiOperation(value = "选项明细", httpMethod = "GET", response = ConfigEntity.class)
    public void query(@ApiParam(value = "关键词") @RequestParam (value = "keyword", required = false) String keyword,
                      @ApiParam(value = "组") @RequestParam (value = "group", required = false) String group,
                      @ApiParam(value = "起始值") @RequestParam (value = "offset") int offset,
                      @ApiParam(value = "每页大小") @RequestParam (value = "length") int length,
                      @ApiParam(value = "排序字段") @RequestParam (value = "sort", required = false) String sort,
                      @ApiParam(value = "排序规则") @RequestParam (value = "order", required = false) String order,
                      HttpServletResponse response)
            throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        Criteria criteria = new Criteria(offset, length);
        criteria.addEntity("ConfigGroupEntity", "groupEntity");
        criteria.add(Restrictions.eqConjunction("entity", "group", "groupEntity.key"));
        if(StringUtils.isNotBlank(keyword))
        {
            criteria.add(Restrictions.or(Restrictions.like("entity","key",keyword, MatchMode.ANYWHERE),
                    Restrictions.like("entity","value",keyword,MatchMode.ANYWHERE)));
        }
        if (StringUtils.isNotEmpty(group)) {
            criteria.add(Restrictions.eq("entity","group", group));
        }
        if(StringUtils.isNotBlank(sort))
            CriterionUtils.addOrder(criteria, "entity."+sort, order, "entity.orderCode");
        else
            criteria.addOrder(Order.desc("entity.orderCode"));
        PagingList<ConfigEntity> entities = ConfigUtils.queryEntity(customer.getOwnerType(),customer.getOwnerId(), criteria);
        Map<String, String> groupMap = new HashMap<String, String>();
        for (ConfigEntity entity : entities) {
            if (groupMap.get(entity.getGroup()) == null) {
                ConfigGroupEntity groupEntity = ConfigUtils.getGroup(entity.getOwnerType(), entity.getOwnerId(),
                        entity.getGroup());
                if (groupEntity != null) {
                    groupMap.put(entity.getGroup(), groupEntity.getValue());
                }
            }
        }
        PagingResult result = PagingResult.getResult(entities);
        result.setParam("group_map", groupMap);
        ResponseUtils.writeSuccessPagingResult(response, result);
    }


    @RequiresAuthentication
    @RequestMapping (value = RoleAction.AddDetail, method = RequestMethod.POST)
    @ApiOperation(value = "添加选项明细", httpMethod = "POST")
    public void AddDetail(@ApiParam(value = "配置项对象") @RequestBody ConfigEntity configEntity, HttpServletResponse response)
            throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        configEntity.setOwnerType(customer.getOwnerType());
        configEntity.setOwnerId(customer.getOwnerId());
        configEntity.setUpdateTime(new Date());
        ConfigUtils.addEntity(configEntity);
        ResponseUtils.writeSuccessResult(response);
    }


    @RequestMapping (value = RoleAction.GETDetail, method = RequestMethod.GET)
    @ApiOperation(value = "获取选项明细", httpMethod = "GET")
    public void GETDetail(@ApiParam(value = "配置项id") @PathVariable long id, HttpServletResponse response)
            throws Exception
    {
        ConfigEntity configEntity = ConfigUtils.getEntity(id);
        ResponseUtils.writeSuccessResult(response, configEntity);
    }

    @RequiresAuthentication
    @RequestMapping (value = RoleAction.UPDATEDetail, method = RequestMethod.PUT)
    @ApiOperation(value = "修改选项明细", httpMethod = "PUT")
    public void UPDATEDetail(@ApiParam(value = "配置项对象") @RequestBody ConfigEntity configEntity, HttpServletResponse response)
            throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        configEntity.setOwnerType(customer.getOwnerType());
        configEntity.setOwnerId(customer.getOwnerId());
        configEntity.setUpdateTime(new Date());
        ConfigUtils.updateEntity(configEntity);
        ResponseUtils.writeSuccessResult(response);
    }
    @RequiresAuthentication
    @RequestMapping (value = RoleAction.DELETEDetail, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除选项明细", httpMethod = "DELETE")
    public void DELETEDetail(@RequestParam ("id") long[] ids, HttpServletResponse response)
            throws Exception
    {
        ConfigUtils.removeEntity(ids);
        ResponseUtils.writeSuccessResult(response);
    }

    @RequestMapping (value = RoleAction.LISTDetail, method = RequestMethod.GET)
    @ApiOperation(value = "根据Key查询明细", httpMethod = "GET")
    public void LISTDetail(@RequestParam ("key") String key,HttpServletResponse response)throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        ResponseUtils.writeSuccessResult(response, ConfigUtils.getConfig(customer.getOwnerType(), customer.getOwnerId(), key));
    }
}
